/**
 * 
 */
package com.qdairlines.controller.user;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qdairlines.common.ControllerUtil;
import com.qdairlines.common.MD5Encoder;
import com.qdairlines.common.Page;
import com.qdairlines.constant.BaseConsts;
import com.qdairlines.constant.DictionaryConsts;
import com.qdairlines.constant.RequestConsts;
import com.qdairlines.entity.user.User;
import com.qdairlines.entity.user.UserRole;
import com.qdairlines.entity.user.UserRoleDto;
import com.qdairlines.service.dict.DictionaryService;
import com.qdairlines.service.user.RoleService;
import com.qdairlines.service.user.UserRoleService;
import com.qdairlines.service.user.UserService;

/**
 * @author pangyannan
 * @date 2017年3月2日
 * @company QingDao Airlines
 * @description 用户控制
 */
@Controller
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleSerivce;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private UserRoleService userRoleService;

	/**
	 * 进入页面
	 * @return
	 */
    @RequestMapping( value = "toPage" ,produces =RequestConsts.PRODUCES)
    public String toPage (HttpServletRequest request,Model model) {
    	model.addAttribute(BaseConsts.LANGUAGE, ControllerUtil.getLanguage(request));
    	return "/user/userlist";
    }
    
    /**
     * 获取用户数据
     * @param request
     * @param workcode
     * @param model
     * @return
     */
    @RequestMapping(value = "getUser" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String getUser(HttpServletRequest request,String workcode,Model model) {
    	User user = userService.getUserByWorkcode(workcode);
     	return ControllerUtil.getJson(user);
    }
     
    /**
     * 用户列表
     * @param request
     * @param roleDataItem
     * @return
     */
	@RequestMapping(value = "getDateList",produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String getDateList(HttpServletRequest request,User user) {
    	Page page = userService.getPageFromRequest(request);
    	page = userService.listData(user, page);
    	return ControllerUtil.getJson(page);
    }
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "listUserByQueryKey",produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String listUserByQueryKey(HttpServletRequest request,String querykey) {
    	Page page = userService.getPageFromRequest(request);
    	page = userService.listUserByQuery(querykey, page);
		List<User> list = page.getRows();
    	dictionaryService.convertDictValueToText(list, "status", "statusName", DictionaryConsts.USER_STATUS, ControllerUtil.getLanguage(request));
    	return ControllerUtil.getJson(page);
    }
    
    /**
     * 保存用户
     * @param request
     * @param dutySchedule
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "save",produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String save(HttpServletRequest request,User user) { 
    	User userCk1 = userService.getUserByWorkcode(user.getWorkcode());
		User userCk2 = userService.getUserByUserName(user.getUserName());
    	
    	if(user.getId() == null){
    		//新增判断
    		if(userCk1 != null || userCk2 != null){
    			return ControllerUtil.getJson(BaseConsts.RESPONSE_MSG_ERROR);
    		}
    		
    		//新增
    		user.setCreateBy(ControllerUtil.getUser(request).getWorkcode());
    		user.setCreateTime(new Date());
    		user.setStatus(BaseConsts.POJO_STATUS_ABLE);
    		userService.save(user);	
    	}else{
    		//修改判断
    		if(userCk1 != null && !user.getId().equals(userCk1.getId())){
    			return ControllerUtil.getJson(BaseConsts.RESPONSE_MSG_ERROR);
    		}
    		if(userCk2 != null && !user.getId().equals(userCk2.getId())){
    			return ControllerUtil.getJson(BaseConsts.RESPONSE_MSG_ERROR);
    		}
    		//修改
    		user.setUpdateBy(ControllerUtil.getUser(request).getWorkcode());
    		user.setUpdateTime(new Date());
    		userService.updateByPrimaryKeySelective(user);
    	}
    	
    	return  JSONObject.fromObject(user).toString();
    }
    
    /**
     * 禁用用户
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "disable" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String disable(Integer id,HttpServletRequest request){
    	User user = new User();
    	user.setId(id);
    	user.setStatus(BaseConsts.POJO_STATUS_DISABLE);
    	user.setUpdateBy(ControllerUtil.getUser(request).getWorkcode());
		user.setUpdateTime(new Date());
		userService.updateByPrimaryKeySelective(user);

		return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_SUCCESS).toString();
    }
    
    /**
     * 启用用户
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "able" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String able(Integer id,HttpServletRequest request){
    	User user = new User();
    	user.setId(id);
    	user.setStatus(BaseConsts.POJO_STATUS_ABLE);
    	user.setUpdateBy(ControllerUtil.getUser(request).getWorkcode());
		user.setUpdateTime(new Date());
		userService.updateByPrimaryKeySelective(user);
    	return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_SUCCESS).toString();
    }
    
	/**
	 * 根据工号查询已经关联的角色，以及未关联的角色  isRelated: Y or N
	 * @param workcode
	 * @param isRelated
	 * @return
	 */
    @RequestMapping(value = "listUserRole" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String listUserRole(String workcode,String isRelated){
    	if(StringUtils.isEmpty(workcode)){
    		return null;
    	}else{
	    	List<UserRoleDto> list = roleSerivce.listUserRoleDtoByWorkcode(workcode,isRelated);
	    	return ControllerUtil.getJson(list);
    	}
    }
    
    /**
	 * 根据工号查询已经关联的角色，以及未关联的角色  isRelated: Y or N
	 * @param workcode
	 * @param isRelated
	 * @return
	 */
    @RequestMapping(value = "getUserRoleCount" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String getUserRoleCount(String workcode,String isRelated){
    	if(StringUtils.isEmpty(workcode)){
    		return null;
    	}else{
	    	List<UserRoleDto> list = roleSerivce.listUserRoleDtoByWorkcode(workcode,isRelated);
	    	return ControllerUtil.getJson(list==null?0:list.size());
    	}
    }
    
    /**
     * 删除用户角色
     * @param userRoleid
     * @param request
     * @return
     */
    @RequestMapping(value = "deleteUserRole" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String Roledisable(Integer userRoleid,HttpServletRequest request){
    	if(userRoleid != null){
	    	userRoleService.deleteByPrimaryKey(userRoleid);
	    	return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_SUCCESS).toString();
    	}
    	return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_ERROR).toString();
    }
    
    /**
     * 添加用户角色
     * @param roleId
     * @param workcode
     * @param request
     * @return
     */
    @RequestMapping(value = "saveUserRole" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String saveUserRole(Integer roleId, String workcode,HttpServletRequest request){
    	UserRole userRole = new UserRole();
    	userRole.setWorkcode(workcode);
    	userRole.setRoleId(roleId);
    	
    	userRole.setCreateBy(ControllerUtil.getUser(request).getWorkcode());
    	userRole.setCreateTime(new Date());
    	
    	userRoleService.saveSelective(userRole);
    	return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_SUCCESS).toString();
    }

    @RequestMapping(value = "deleteUserRoleByUidRid" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String deleteUserRoleByUidRid(@RequestParam Integer roleId, @RequestParam String workcode,HttpServletRequest request){
    	UserRole ur = new UserRole();
    	ur.setRoleId(roleId);
    	ur.setWorkcode(workcode);
    	List<UserRole> userRolelist = userRoleService.listData(ur);
    	if(userRolelist != null && userRolelist.size()>0){
    		for(UserRole userRole : userRolelist){
    			userRoleService.deleteByPrimaryKey(userRole.getId());
    		}
    	}
    	return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_SUCCESS).toString();
    }
    
    
    @RequestMapping(value = "toChangePasswordPage" ,produces = RequestConsts.PRODUCES)
    public String toChangePasswordPage(@RequestParam Integer userId,Model model){
    	model.addAttribute("userId", userId);
    	return "/user/changePassword";
    }
    
    @RequestMapping(value = "changePassword" ,produces = RequestConsts.PRODUCES)
    @ResponseBody
    public String changePassword(@RequestParam Integer userId,@RequestParam String password){
    	String passwordMd5 = MD5Encoder.encode(password);
    	User user = new User();
    	user.setId(userId);
    	user.setPassword(passwordMd5);
    	
    	userService.updateByPrimaryKeySelective(user);
    	return JSONObject.fromObject(BaseConsts.RESPONSE_MAP_SUCCESS).toString();
    }
}
